package com.shelpe.services.sinbad.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.shelpe.services.sinbad.entity.jpa.Adgroup;
import com.shelpe.services.sinbad.entity.jpa.Campaign;
import com.shelpe.services.sinbad.entity.jpa.OnlineStatus;
import com.shelpe.services.sinbad.model.Keyword;
import com.shelpe.services.sinbad.model.KeywordExample;
import com.shelpe.services.sinbad.model.RptKeyword;
import com.shelpe.services.sinbad.model.RptKeywordParam;
import com.shelpe.services.sinbad.readdao.KeywordMapper;
import com.shelpe.services.sinbad.repository.jpa.AdgroupRepository;
import com.shelpe.services.sinbad.repository.jpa.CampaignRepository;
import com.shelpe.services.sinbad.service.RptKeywordService;

import io.swagger.annotations.Api;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Controller
@Api("关键词相关API（旧）")
@RequestMapping("/sinbadservice")
public class KeywordController {

	@Autowired
	private KeywordMapper keywordMapper;
	@Autowired
	private RptKeywordService rptKeywordService;
	@Autowired
	private AdgroupRepository adgroupRepository;
	@Autowired
	private CampaignRepository campaignRepository;

	/**
	 * 卡位详情调用
	 * 
	 * @param keywordId
	 * @return
	 */
	@RequestMapping("/users/{userId}/keywords/{keywordId}/data")
	public @ResponseBody RptKeyword keywrodData(@PathVariable("userId") Long userId,
			@PathVariable("keywordId") Long keywordId, @RequestParam(defaultValue = "7") Integer days,
			@RequestParam(required = false) Integer device) {
		log.info("s RequestParam userId:{} keywordId:{} days:{} device:{}", userId, keywordId, days, device);
		RptKeywordParam param = new RptKeywordParam();
		param.setUserId(userId);
		param.setKeywordId(keywordId);
		param.setDay(days);
		if (device != null) {
			param.setSource(device.byteValue());
		}
		return rptKeywordService.selectSum(param);
	}

	/**
	 * 删除垃圾词 - 查询符合条件的垃圾词
	 * 
	 * @param userId
	 *            用户ID
	 * @param campaignIds
	 *            推广计划ids
	 * @param adgroupIds
	 *            推广组ids
	 * @param clickDay
	 *            查询点击量的天数
	 * @param impressionsDay
	 *            查询展现量的天数
	 * @param qscore
	 *            PC质量得分
	 * @param mobileQscore
	 *            无线质量得分
	 * @return
	 */
	@RequestMapping(method = RequestMethod.GET, value = "/spamwords")
	public @ResponseBody SpamKeywordsDto spamwords(@RequestParam(required = false) Long userId,
			@RequestParam(required = false) List<Long> campaignIds,
			@RequestParam(required = false) List<Long> adgroupIds, @RequestParam(required = false) Integer clickDay,
			@RequestParam(required = false) Integer impressionsDay, @RequestParam(required = false) Integer qscore,
			@RequestParam(required = false) Integer mobileQscore) {
		long start = System.currentTimeMillis();

		if (userId == null) {
			if (adgroupIds != null && adgroupIds.size() > 0) {
				Adgroup adgroup = adgroupRepository.findOne(adgroupIds.get(0));
				userId = adgroup.getUserID();
			} else if (campaignIds != null && campaignIds.size() > 0) {
				Campaign campaign = this.campaignRepository.findOne(campaignIds.get(0));
				userId = campaign.getUserID();
			}

			if (userId == null) {
				throw new IllegalArgumentException("userID_not_found");
			}
		}

		RptKeywordParam param = new RptKeywordParam();
		param.setUserId(userId);
		if (adgroupIds != null && adgroupIds.size() > 0) {
			param.setAdgroupIds(adgroupIds);
		}
		if (campaignIds != null && campaignIds.size() > 0) {
			param.setCampaignIds(campaignIds);
		}
		if (clickDay != null) {
			param.setClickDay(clickDay);
		}
		if (impressionsDay != null) {
			param.setImpressionsDay(impressionsDay);
		}
		if (qscore != null) {
			param.setQscore(qscore);
		}
		if (mobileQscore != null) {
			param.setMobileQscore(mobileQscore);
		}

		List<RptKeywordService.KeywordCompositeID> ids = rptKeywordService.getKeywordIds(param);
		SpamKeywordsDto dto = new SpamKeywordsDto();
		dto.setUserID(userId);
		if (ids != null && ids.size() > 0) {
			// 查看在keyword表中是否存在
			List<Long> foundKeywordIDs = new ArrayList<Long>();
			for (RptKeywordService.KeywordCompositeID id : ids) {
				foundKeywordIDs.add(id.getKeywordID());
			}
			KeywordExample ke = new KeywordExample();
			ke.setUserId(userId);
			ke.createCriteria().andKeywordIdIn(foundKeywordIDs);
			List<Keyword> foundKeywords = this.keywordMapper.selectByExample(ke);
			// 查看对应的adgroup是否存在
			List<Long> adgroupIDs = new ArrayList<Long>();
			for (Keyword kw : foundKeywords) {
				adgroupIDs.add(kw.getAdgroupId());
			}
			List<Adgroup> adgroups = this.adgroupRepository.findByAutoIDIn(adgroupIDs);
			adgroupIDs = new ArrayList<Long>();
			for (Adgroup adgroup : adgroups) {
				if (adgroup.getOnlineStatus() != OnlineStatus.offline) {
					adgroupIDs.add(adgroup.getAutoID());
				}
			}

			// 最终有效的keyword_id
			foundKeywordIDs = new ArrayList<Long>();
			for (Keyword kw : foundKeywords) {
				if (adgroupIDs.indexOf(kw.getAdgroupId()) > -1) {
					foundKeywordIDs.add(kw.getKeywordId());
				}
			}

			dto.setCount(foundKeywordIDs.size());
			Map<Long, CampaignSpamKeywords> map = new HashMap<Long, CampaignSpamKeywords>();
			for (RptKeywordService.KeywordCompositeID id : ids) {
				if (foundKeywordIDs.contains(id.getKeywordID())) {
					CampaignSpamKeywords csk = map.get(id.getCampaignID());
					if (csk == null) {
						csk = new CampaignSpamKeywords();
						csk.setCampaignID(id.getCampaignID());
						map.put(id.getCampaignID(), csk);
					}
					csk.addKeywordID(id.getKeywordID());
				}
			}
			dto.setKeywords(new ArrayList<CampaignSpamKeywords>());
			for (CampaignSpamKeywords csk : map.values()) {
				dto.getKeywords().add(csk);
			}
		}

		log.info("select spamwords cost {} ms", System.currentTimeMillis() - start, param);
		return dto;
	}

	@Data
	@JsonInclude(Include.NON_NULL)
	public static class SpamKeywordsDto {
		private int count;
		@JsonProperty("user_id")
		private long userID;
		private List<CampaignSpamKeywords> keywords;
	}

	@Data
	private static class CampaignSpamKeywords {
		@JsonProperty("campaign_id")
		private long campaignID;
		@JsonProperty("keyword_ids")
		private List<Long> keywordIDs;

		public void addKeywordID(long keywordID) {
			if (this.keywordIDs == null) {
				this.keywordIDs = new ArrayList<Long>();
			}
			this.keywordIDs.add(keywordID);
		}
	}

}
